package com.example.seckill.controller;


import com.example.seckill.controller.co.ItemCO;
import com.example.seckill.controller.vo.ItemVo;
import com.example.seckill.mappstruct.ItemMap;
import com.example.seckill.response.CommonReturnType;
import com.example.seckill.service.ItemService;
import com.example.seckill.service.model.ItemModel;
import com.example.seckill.service.model.PromoModel;
import com.google.common.cache.Cache;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.ZoneOffset;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

@Slf4j
@RestController
@RequestMapping("/item")
public class ItemController {
    private static final String ITEM_PREFIX = "ITEM_";
    @Autowired
    private ItemService itemService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private Cache<String, Object> guavaCache;
    @Autowired
    private Cache<String, Object> caffeineCache;

    @GetMapping("/getById")
    public CommonReturnType getById(@RequestParam("id") Integer id) throws ExecutionException {
        ItemModel itemModel=null;
//        itemModel=(ItemModel)caffeineCache.get(ITEM_PREFIX + id, () -> itemService.findById(id));
//        itemModel = (ItemModel) redisTemplate.opsForValue().get(ITEM_PREFIX + id);
        itemModel = (ItemModel)guavaCache.get(ITEM_PREFIX + id, () -> itemService.findById(id));
//        if (itemModel == null) {
//            itemModel = itemService.findById(id);
//            redisTemplate.opsForValue().set(ITEM_PREFIX + id,itemModel);
//            guavaCache.put(ITEM_PREFIX + id,itemModel);
//        }
        ItemVo itemVo = convertFromModel(itemModel);
        return CommonReturnType.create(itemVo);
    }

    private ItemVo convertFromModel(ItemModel itemModel) {
        ItemVo itemVo = ItemMap.INSTANCE.Model2Vo(itemModel);
        PromoModel promoModel = itemModel.getPromoModel();
        if (promoModel != null) {
            itemVo.setPromoPrice(promoModel.getPromoPrice());
            itemVo.setStartDate(promoModel.getStartDate().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
            itemVo.setPromoId(promoModel.getPromoId());
        }
        return itemVo;
    }

    @GetMapping("/getAll")
    public CommonReturnType getAll()  {
        List<ItemModel> itemModels = itemService.findAll();
        List<ItemVo> itemVos = ItemMap.INSTANCE.Model2VoList(itemModels);
        return CommonReturnType.create(itemVos);
    }

    @PostMapping("/insert")
    public CommonReturnType insert(@RequestBody ItemCO itemCO){
        ItemModel itemModel = ItemMap.INSTANCE.CO2Model(itemCO);
        itemModel = itemService.insert(itemModel);
        return CommonReturnType.create(itemModel);
    }


}
